package com.linked.store.delivery.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.linked.store.delivery.bean.po.DeliveryInfoPO;
import com.linked.store.delivery.service.IDeliveryService;
import com.linked.store.thing.service.IThingHandleService;
import com.linked.universal.common.LinkedPrompt;
import com.linked.universal.common.LinkedResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

/**
 * @author :dbq
 * @date : 2023/7/3 13:23
 * @description : desc
 */
@RestController
@RequestMapping("delivery")
@Slf4j
public class DeliveryController {

    private final IDeliveryService deliveryService;

    private final ObjectMapper mapper;

    private final IThingHandleService thingHandleService;

    private final StringRedisTemplate redisTemplate;

    public DeliveryController(IDeliveryService deliveryService, ObjectMapper mapper, IThingHandleService thingHandleService, StringRedisTemplate redisTemplate) {
        this.deliveryService = deliveryService;
        this.mapper = mapper;
        this.thingHandleService = thingHandleService;
        this.redisTemplate = redisTemplate;
    }

    @PostMapping("confirmDelivery")
    LinkedResult confirmDelivery(@RequestBody DeliveryInfoPO param) throws Exception {

        /**
         * 校验排队号是否超时
         * */
        String redisKey_lineUp = "GoodsLine_" + param.getGoodsVersionId() + "_" + param.getOrderId();
        if (!redisTemplate.hasKey(redisKey_lineUp)) {
            return LinkedResult.CheckFailure(LinkedPrompt.ORDER_TIME_OUT);
        }
        /**
         * 扣减真实库存
         * */
        boolean ret = false;
        String redisKey = "LockGoods_" + param.getGoodsVersionId();

        while (!redisTemplate.opsForValue().setIfAbsent(redisKey, "locked", 30, TimeUnit.SECONDS)) {
            Thread.sleep(100);
        }
        try {
            ret = thingHandleService.reduceInventory(param.getGoodsVersionId(), param.getGoodsCount());
        } catch (Exception e) {
            log.error("扣减库存借口 异常", e);
            return LinkedResult.Error(LinkedPrompt.ERROR_MESSAGE);
        } finally {
            redisTemplate.delete(redisKey);
        }
        /**
         * 保存配送单
         * */

        boolean ret_delivery = false;
        try {
            ret_delivery = deliveryService.saveDelivery(param);
        } catch (Exception e) {
            log.error("确认发货接口 异常！", e);
            return LinkedResult.Error(LinkedPrompt.ERROR_MESSAGE);
        }

        return ret_delivery ? LinkedResult.Success() : LinkedResult.OK(false, LinkedPrompt.OPERATION_FAILED);

    }
}
